import { BrowserWindow, dialog, ipcMain, IpcMainEvent, shell } from 'electron'
import autoUpdater from '../autoUpdater'

import { downloadFile } from '../uitil'
import { getByNameWindow } from '../windows'

ipcMain.on('miniWindow', (_event: IpcMainEvent, name: WindowNameType) => {
  getByNameWindow(name).minimize()
})
ipcMain.on('screenWindow', (_event: IpcMainEvent, name: WindowNameType, isMax: boolean) => {
  if (isMax) {
    getByNameWindow(name).maximize()
  } else {
    getByNameWindow(name).unmaximize()
  }
})
ipcMain.on('openWindow', (_event: IpcMainEvent, name: WindowNameType, params?: any) => {
  getByNameWindow(name, params).show()
})
ipcMain.on('closeWindow', (_event: IpcMainEvent, name: WindowNameType, type: WindowCloseType) => {
  if (name == 'basiceQuipment') {
    getByNameWindow('findSearch').destroy()
  }
  getByNameWindow(name)[type]()
})
ipcMain.on('setWindowHeight', (_event: IpcMainEvent, name: WindowNameType, windowHeight: number) => {
  const win = getByNameWindow(name)
  win.setSize(win.getSize()[0], windowHeight)
})
ipcMain.on('downloadFile', async (_event: IpcMainEvent, fileUrl: string, fileName: string) => {
  const res = await dialog.showSaveDialog({
    title: '下载文件',
    message: '装企财多多桌面软件',
    defaultPath: fileName,
    properties: ['createDirectory'],
  })
  if (res.canceled === false && res.filePath) downloadFile(fileUrl, res.filePath)
})
ipcMain.on('closeAllWindow', (_event: IpcMainEvent) => {
  const allWindows = BrowserWindow.getAllWindows()
  getByNameWindow('login').show()
  allWindows.forEach((item: BrowserWindow) => {
    item.destroy()
  })
})
ipcMain.on('openChorm', (_event: IpcMainEvent, chormUrl: string) => {
  shell.openExternal(chormUrl)
})
ipcMain.on('checkUpdate', (_event: IpcMainEvent) => {
  const win = getByNameWindow('config')
  autoUpdater(win)
})
ipcMain.on('refreshInitData', (_event: IpcMainEvent) => {
  const win = getByNameWindow('config')
  win.webContents.send('refreshData')
})
ipcMain.on('refreshCostData', (_event: IpcMainEvent, house_type: number) => {
  if (house_type == 1) {
    const win = getByNameWindow('basiceQuipment')
    win.webContents.send('refCostData')
  } else {
    const win = getByNameWindow('total')
    win.webContents.send('refCostData')
  }
})
// 查找窗口向主窗口发送消息
ipcMain.on(
  'findSendMsg',
  (
    _event: IpcMainEvent,
    name: WindowNameType,
    handleType: String,
    currentPage: String,
    content: String,
    replaceContent?: String,
    editIds?: String,
  ) => {
    const win = getByNameWindow(name)
    win.webContents.send('acceptSendMsg', handleType, currentPage, content, replaceContent, editIds)
  },
)
ipcMain.on('sendListArray', (_event: IpcMainEvent, dataList: string) => {
  const win = getByNameWindow('findSearch')
  win.webContents.send('pushDataLit', dataList)
})
